package com.jgp.glmeeting.mobile.commons;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import com.alibaba.fastjson.JSON;

public class HttpGetUtil {
	 public static String httpRequestToString(String url,   
	            Map<String,String> params) {  
        String result = null;  
        try {  
            InputStream is = httpRequestToStream(url,  params);  
            BufferedReader in = new BufferedReader(new InputStreamReader(is,  
                    "UTF-8"));  
            StringBuffer buffer = new StringBuffer();  
            String line = "";  
            while ((line = in.readLine()) != null) {  
                buffer.append(line);  
            }  
            result = buffer.toString();  
        } catch (Exception e) {  
        	e.printStackTrace();
        }  
        return result;  
    }  
	  
    private static InputStream httpRequestToStream(String url,  
            Map<String, String> params) {  
        InputStream is = null;  
        try {  
            String parameters = "";  
            boolean hasParams = false;  
            for(String key : params.keySet()){  
                String value = URLEncoder.encode(params.get(key), "UTF-8");  
                parameters += key +"="+ value +"&";  
                    hasParams = true;  
            }  
            if(hasParams){  
                parameters = parameters.substring(0, parameters.length()-1);  
            }  
  
            url += "?"+ parameters;  
            
            URL u = new URL(url);  
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();  
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
            conn.setRequestProperty("Accept-Charset", "UTF-8");  
            conn.setRequestProperty("contentType", "utf-8");  
            conn.setConnectTimeout(50000);    
            conn.setReadTimeout(50000);  
            conn.setDoInput(true);  
            //设置请求方式，默认为GET  
            conn.setRequestMethod("GET");  
  
            is = conn.getInputStream();
            return is;
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    } 
    
  /*  public static String sendPostMessage(String strUrl,Map<String, String> params) {

		URL url = null;
		try {
			url = new URL(strUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		
		StringBuffer stringBuffer = new StringBuffer();
		
		if (params != null && !params.isEmpty()) {
		for (Map.Entry<String, String> entry : params.entrySet()) {
			try {
				stringBuffer.append(entry.getKey()).append("=").
					append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
			
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// 删掉最后一个 & 字符
		stringBuffer.deleteCharAt(stringBuffer.length() - 1);
		System.out.println("-->>" + stringBuffer.toString());
		
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(3000);
			httpURLConnection.setDoInput(true);// 从服务器获取数据
			httpURLConnection.setDoOutput(true);// 向服务器写入数据
			
			// 获得上传信息的字节大小及长度
			byte[] mydata = stringBuffer.toString().getBytes();
			// 设置请求体的类型
			httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Content-Lenth",String.valueOf(mydata.length));
			
			// 获得输出流，向服务器输出数据
			OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();
			outputStream.write(mydata);
			
			// 获得服务器响应的结果和状态码
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {
				// 获得输入流，从服务器端获得数据
				InputStream is = (InputStream) httpURLConnection.getInputStream();
				BufferedReader in = new BufferedReader(new InputStreamReader(is,  
	                    "UTF-8"));  
	            StringBuffer buffer = new StringBuffer();  
	            String line = "";  
	            while ((line = in.readLine()) != null) {  
	                buffer.append(line);  
	            }  
	            String result = buffer.toString();
	            return result;
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
		}
		
		return "";
	}*/
    public static String jsonPost(String strURL, Map<String, String> params) {  
        try {  
            URL url = new URL(strURL);// 创建连接  
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
            connection.setDoOutput(true);  
            connection.setDoInput(true);  
            connection.setUseCaches(false);  
            connection.setInstanceFollowRedirects(true);  
            connection.setRequestMethod("POST"); // 设置请求方式  
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式  
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式  
            connection.connect();  
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码  
//            out.append(JSONUtil.object2JsonString(params)); 
            out.append(JSON.toJSONString(params));
            
            out.flush();  
            out.close();  
  
            int code = connection.getResponseCode();  
            InputStream is = null;  
            if (code == 200) {  
                is = connection.getInputStream();  
            } else {  
                is = connection.getErrorStream();  
            }  
  
            // 读取响应  
            int length = (int) connection.getContentLength();// 获取长度  
            if (length != -1) {  
                byte[] data = new byte[length];  
                byte[] temp = new byte[512];  
                int readLen = 0;  
                int destPos = 0;  
                while ((readLen = is.read(temp)) > 0) {  
                    System.arraycopy(temp, 0, data, destPos, readLen);  
                    destPos += readLen;  
                }  
                String result = new String(data, "UTF-8"); // utf-8编码  
                return result;  
            }  
  
        } catch (IOException e) {  
        	e.printStackTrace();    
        }  
        return "error"; // 自定义错误信息  
    }  
    //提交post请求
/*    public static String httpPost(String url,  
            Map<String, String> params) {
    	InputStream is = null; 
		try {
			String parameters = "";  
            boolean hasParams = false;  
            for(String key : params.keySet()){  
                String value = URLEncoder.encode(params.get(key), "UTF-8");  
                parameters += key +"="+ value +"&";  
                    hasParams = true;  
            }  
            if(hasParams){  
                parameters = parameters.substring(0, parameters.length()-1);  
            } 
            URL u = new URL(url);
		 
	        HttpURLConnection conn = (HttpURLConnection) u.openConnection();  
	        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
	        conn.setRequestProperty("Accept-Charset", "UTF-8");  
	        conn.setRequestProperty("contentType", "utf-8");  
	        conn.setConnectTimeout(50000);    
	        conn.setReadTimeout(50000);  
	        conn.setDoInput(true);  
	        //设置请求方式，默认为GET  
	        conn.setRequestMethod("POST");  
	
	        is = conn.getInputStream(); 
	        BufferedReader in = new BufferedReader(new InputStreamReader(is,  
                    "UTF-8"));  
            StringBuffer buffer = new StringBuffer();  
            String line = "";  
            while ((line = in.readLine()) != null) {  
                buffer.append(line);  
            }  
            String result = buffer.toString(); 
            return result;
		} catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        } catch (MalformedURLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return null;
    }*/
    
    
}
